import socket
from _thread import *
import pickle
from game import Game

def threaded_client(conn, p, gameId):
    global idCount
    conn.send(str.encode(str(p)))
    data = conn.recv(4096).decode()
    if data != "ready":
        return None

    while True:
        try:
            if gameId in games:
                game = games[gameId]
                game.play_phase1(p)
                games[gameId] = game

                conn.send(pickle.dumps(game.playerCards[p]))
                data = conn.recv(4096).decode()
                if not data:
                    break
                game.get_player_cards(p, pickle.loads(data))
                games[gameId] = game

                while not game.bothReady():
                    game = games[gameId]
                    pass

                game.play_phase2(p)
                game = games[gameId]
                while not (game.phase2[0] and game.phase2[1]):
                    game = games[gameId]
                    pass

                game.turns_settlement(p)
                game = games[gameId]
                while not (game.settlement[0] and game.settlement[1]):
                    game = games[gameId]
                    pass
            else:
                break
        except:
            break

    print("Lost connection")
    try:
        del games[gameId]
        print("Closing Game", gameId)
    except:
        pass
    idCount -= 1
    conn.close()

if __name__ == '__main__':
    host = "192.168.0.107"
    port = 8081

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        server.bind((host, port))
    except socket.error as e:
        str(e)

    server.listen(2)
    print("Waiting for a connection, Server Started")

    connected = set()
    games = {}
    idCount = 0

    while True:
        conn, addr = server.accept()
        print("Connected to:", addr)

        idCount += 1
        p = 0
        gameId = (idCount - 1)//2
        if idCount % 2 == 1:
            games[gameId] = Game(gameId)
            print("Creating a new game...")
        else:
            games[gameId].ready = True
            p = 1

    start_new_thread(threaded_client, (conn, p, gameId))